package com.reebake.ideal.response.wrapper.config;

import cn.hutool.core.util.ObjUtil;
import com.reebake.ideal.response.wrapper.properties.ResponseBodyWrapperProperties;
import com.reebake.ideal.servlet.core.ResponseBodyWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class GlobalResponseBodyWrapper implements ResponseBodyAdvice<Object> {
    @Autowired
    private ResponseBodyWrapperProperties responseBodyWrapperProperties;
    @Autowired(required = false)
    private ResponseBodyWrapper responseBodyWrapper;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if(ObjUtil.isNull(responseBodyWrapper)) {
            return false;
        }
        for(Class<?> clazz : responseBodyWrapperProperties.getIgnoreWrapperTypes()) {
            if(returnType.getParameterType().equals(clazz)){
                return false;
            }
        }
        if(returnType.getParameterType().equals(ResponseEntity.class)) {
            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        for(String pattern : responseBodyWrapperProperties.getIgnoreWrapperUrls()) {
            String path = request.getURI().getPath();
            if(antPathMatcher.match(pattern, path)) {
                return body;
            }
        }
        return responseBodyWrapper.convert(body);
    }
}
